# -*- coding: utf-8 -*-

import requests
from lxml import etree
from tools.auxiliary_tools import normalization
from tools.mysqlconn import NBAdb
from mysql_text import sql_coach_insert
from tools.log_tool import Logger


class Coachdata:

    def __init__(self):
        """
        初始化一些数据。
        """
        self.headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36'
        }
        self.log_instance = Logger('../test/log/get_coach_data.log')

    def coach_data(self, url, name):
        """
        获取教练页面中的数据，教练所有的数据都在同一个URL中，所以只需要建立一个函数一次获取。
        5个表：教练个人简介表、教练常规赛数据表、教练常规赛总计表、教练季后赛数据表、教练季后赛总计表。
        :param url: 教练的URL
        :param name: 教练的名字
        :return:
        """
        res = requests.get(url, headers=self.headers)
        res.encoding = 'utf-8'
        html_lxml = etree.HTML(res.text)
        one = NBAdb()

        """
        获取教练个人简介表
        """
        content_one = html_lxml.xpath('//div[@class="detail"]')

        # 出生日期
        try:
            bi_birthday = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"出生日期:")]/../text()'))[0]
        except:
            bi_birthday = ''

        # 出生城市
        try:
            bi_hometown = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"出生城市:")]/../text()'))[0]
        except:
            bi_hometown = ''

        # 高中
        try:
            bi_highschool = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"高　　中:")]/../text()'))[0]
        except:
            bi_highschool = ''

        # 大学
        try:
            bi_university = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"大　　学:")]/../text()'))[0]
        except:
            bi_university = ''

        # 执教生涯
        try:
            bi_teaching_career = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"执教生涯:")]/../text()'))[0]
        except:
            bi_teaching_career = ''

        # 常规赛
        try:
            bi_season = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"常")]/../text()'))[0]
        except:
            bi_season = ''

        # 季后赛
        try:
            bi_playoff = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"季")]/../text()'))[0]
        except:
            bi_playoff = ''

        # 总决赛
        try:
            bi_finals = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"决")]/../text()'))[0]
        except:
            bi_finals = ''

        # 总冠军
        try:
            bi_champion = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"冠")]/../text()'))[0]
        except:
            bi_champion = ''

        # 最佳教练
        try:
            bi_best_coach = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"最佳教练:")]/../text()'))[0]
        except:
            bi_best_coach = ''

        # 名人堂
        try:
            bi_hall_of_fame = normalization(content_one[0].xpath('.//div[@class="column"][contains(text(),"人")]/../text()'))[0]
        except:
            bi_hall_of_fame = ''

        # 存放球员个人简介数据的列表
        bi_list = [name, bi_birthday, bi_hometown, bi_highschool, bi_university, bi_teaching_career,
                   bi_season, bi_playoff, bi_finals, bi_champion, bi_best_coach, bi_hall_of_fame]
        # 插入数据
        one.insert_data(sql_coach_insert.insert_coach_brief_introduction, bi_list)
        self.log_instance.logger.info(name + '的数据已经成功插入数据库...')

        """
        获取教练常规赛数据表、获取教练常规赛总计表
        """
        if html_lxml.xpath('//div[@id="stat_box"]//table/tbody'):
            # 获取教练常规赛数据表
            content_two = html_lxml.xpath('//div[@id="stat_box"]//table/tbody/tr[@class="openoppo"]')
            for i in content_two:
                sd_list = [name]
                list_ls = i.xpath('./td//text()')
                sd_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_season_data, sd_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')

            # 获取教练常规赛总计表
            content_two = html_lxml.xpath(
                '//div[@id="stat_box"]//table/tbody/tr[not(@class="openoppo" or @class="oppo")]')
            if len(content_two) == 3:
                sdc_list = [name]
                list_ls = html_lxml.xpath('//div[@id="stat_box"]//table/tbody/tr[last()-1]/td//text()')
                sdc_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_season_data_count, sdc_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')
            else:
                sdc_list = [name]
                list_ls = html_lxml.xpath('//div[@id="stat_box"]//table/tbody/tr[last()]/td//text()')
                sdc_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_season_data_count, sdc_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')

        """
        获取教练季后赛数据表、获取教练季后赛总计表
        """
        if html_lxml.xpath('//div[@id="stat_box2"]//table/tbody'):
            # 获取教练常规赛数据表
            content_three = html_lxml.xpath('//div[@id="stat_box2"]//table/tbody/tr[@class="openoppo"]')
            for i in content_three:
                pd_list = [name]
                list_ls = i.xpath('./td//text()')
                pd_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_playoff_data, pd_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')

            # 获取教练常规赛总计表
            content_three = html_lxml.xpath(
                '//div[@id="stat_box2"]//table/tbody/tr[not(@class="openoppo" or @class="oppo")]')
            if len(content_three) == 3:
                pdc_list = [name]
                list_ls = html_lxml.xpath('//div[@id="stat_box2"]//table/tbody/tr[last()-1]/td//text()')
                pdc_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_playoff_data_count, pdc_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')
            else:
                pdc_list = [name]
                list_ls = html_lxml.xpath('//div[@id="stat_box2"]//table/tbody/tr[last()]/td//text()')
                pdc_list.extend(list_ls)
                one.insert_data(sql_coach_insert.insert_coach_playoff_data_count, pdc_list)
                self.log_instance.logger.info(name + '的数据已经成功插入数据库...')

        del one


if __name__ == '__main__':
    test_one = Coachdata()
    url = 'http://www.stat-nba.com/coach/136.html'
    name = '菲尔-杰克逊/Phil Jackson'
    test_one.get_data(url, name)
